from django.contrib import admin
from .models import Lecture, Tag
from .classTime import startIndex, endIndex
from .yuque import upload, del_doc


@admin.register(Tag)
class TagAdmin(admin.ModelAdmin):
    list_display = ["id", "name"]


@admin.register(Lecture)
class LectureAdmin(admin.ModelAdmin):
    list_display = ("title", "tag_list")
    filter_horizontal = ("tag",)
    exclude = ("startIndex", "endIndex", "accurate", "slug", "docID", "count")

    def save_model(self, request, obj: Lecture, form, change):
        obj.startIndex, a = startIndex(obj.startTime)
        obj.endIndex, b = endIndex(obj.endTime)
        obj.accurate = a and b
        # 当开始结束都在12-14时，判断结果为第五节开始，第四节结束
        if obj.startIndex == 5 and obj.endIndex == 4:
            obj.startIndex = 4
            obj.endIndex = 5
            obj.accurate = False
        if obj.slug != "":
            del_doc(obj.docID)
        obj.tag_list_str = [x.name for x in form.cleaned_data["tag"]]
        obj.docID, obj.slug = upload(obj)
        return obj.save()

    def delete_model(self, request, obj):
        del_doc(obj.docID)
        return obj.delete()
